package com.srwl.mytx.adapter;


import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.recyclerview.widget.RecyclerView;

import com.srwl.mytx.Constant;
import com.srwl.mytx.EaseConstant;
import com.srwl.mytx.Helper;
import com.srwl.mytx.R;
import com.srwl.mytx.RetrofitManager;
import com.srwl.mytx.activity.BaseActivity;
import com.srwl.mytx.activity.ForwardDetailsActivity;
import com.srwl.mytx.activity.UserProfileActivity;
import com.srwl.mytx.domain.CommonResult;
import com.srwl.mytx.domain.Donation;
import com.srwl.mytx.domain.User;
import com.srwl.mytx.service.DonationService;
import com.srwl.mytx.utils.ClickUtil;
import com.srwl.mytx.utils.DateUtils;
import com.srwl.mytx.utils.GlideLoadUtils;
import com.srwl.mytx.utils.Utils;

import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * 主题收到的捐赠记录适配器
 */
public class TopicDonationRecordAdapter extends RecyclerView.Adapter<TopicDonationRecordAdapter.ReceivedDonationViewHolder> {
    private static final String TAG = "TopicDonationRecordAdap";
    private final List<Donation> donationList;
    private final Context context;
    private InteractionListener listener;


    public TopicDonationRecordAdapter(Context context, List<Donation> donationList, InteractionListener listener) {
        this.donationList = donationList;
        this.context = context;
        this.listener = listener;
    }


    @Override
    public ReceivedDonationViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {

        return new ReceivedDonationViewHolder(LayoutInflater.from(context).inflate(R.layout.layout_received_donation_record_item, parent, false));

    }

    @Override
    public void onBindViewHolder(final ReceivedDonationViewHolder viewHolder, final int position) {
        final Donation donation = donationList.get(position);
        User targetUser = donation.getTargetUser();
        if (targetUser != null) {
            viewHolder.iv_avatar.setVisibility(View.VISIBLE);
            viewHolder.tv_name.setVisibility(View.VISIBLE);
            GlideLoadUtils.glideLoad(context, targetUser.getAvatar(), viewHolder.iv_avatar);
            viewHolder.tv_name.setText(targetUser.getUsername());
            viewHolder.tv_address.setText(targetUser.getArea());
            viewHolder.iv_avatar.setOnClickListener(v -> toUserProfile(targetUser));
            viewHolder.tv_name.setOnClickListener(v -> toUserProfile(targetUser));
            viewHolder.tv_address.setOnClickListener(v -> toUserProfile(targetUser));
        } else {
            viewHolder.iv_avatar.setVisibility(View.INVISIBLE);
            viewHolder.tv_name.setVisibility(View.INVISIBLE);
        }

        Integer type = donation.getType();
        if (type != null) {
            if (type == Constant.DONATION_TYPE_ADVERTISEMENT) {//广告产生的捐赠
                handleAdvertisementDonation(viewHolder, donation);
            } else {//个人捐出
                handlePersonDonation(viewHolder, donation);
            }

        }
        viewHolder.tv_extraMessage.setText(donation.getExtra());
        viewHolder.tv_amount.setText(Utils.moneyFormat(donation.getAmount()));
        Date date = donation.getUpdated() != null ? donation.getUpdated() : donation.getCreated();
        viewHolder.tv_date.setText(DateUtils.getTimestampString(date));

        viewHolder.tv_donationPraiseSize.setText(Utils.numberFormat(donation.getPraiseSize()));
         Boolean hasPraise = donation.getHasPraise();
        if (hasPraise==null){
            hasPraise=false;
        }
        if ( hasPraise) {
            viewHolder.iv_donationPraise.setImageResource(R.drawable.tx_good_red);
        } else {
            viewHolder.iv_donationPraise.setImageResource(R.drawable.tx_good_gray);
        }
        Boolean finalHasPraise = hasPraise;
        viewHolder.ll_donationPraise.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (finalHasPraise) {
                    removeDonationPraise(donation, viewHolder);
                } else {
                    donationPraise(donation, viewHolder);
                }
            }
        });
    }

    /**
     * 个人捐出的，在没有转赠之前，可以拆回
     * @param viewHolder
     * @param donation
     */
    private void handlePersonDonation(ReceivedDonationViewHolder viewHolder, Donation donation) {
        Integer status = donation.getStatus();
        if (status != null) {
            if (status == Constant.DONATION_STATUS_COULD_REVOKE || status == Constant.DONATION_STATUS_COULD_NOT_REVOKE) {
                viewHolder.tv_status.setVisibility(View.VISIBLE);
                viewHolder.tv_status.setText("[个人捐赠]");//显示类型
            } else if (status == Constant.DONATION_STATUS_FORWARD) {
                donationHadForward(viewHolder, donation);
            } else if (status == Constant.DONATION_STATUS_ACTIVE_REVOKE) {
                viewHolder.tv_status.setVisibility(View.VISIBLE);
                viewHolder.tv_status.setText("[已拆回]");
                viewHolder.tv_status.setTextColor(context.getResources().getColor(R.color.text_gray));
            } else if (status == Constant.DONATION_STATUS_PASSIVE_REVOKE) {
                viewHolder.tv_status.setText("[已取消]");
                viewHolder.tv_status.setTextColor(context.getResources().getColor(R.color.text_gray));
            } else {
                Log.e(TAG, "onBindViewHolder: 还有状态未处理" + donation.toString());
            }
        }
    }

    /**
     * 捐赠已经转发
     * @param viewHolder
     * @param donation
     */
    private void donationHadForward(ReceivedDonationViewHolder viewHolder, Donation donation) {
        viewHolder.tv_status.setVisibility(View.VISIBLE);
        viewHolder.tv_status.setText("[已转赠]");
        viewHolder.tv_status.setTextColor(context.getResources().getColor(R.color.text_black));
        viewHolder.ll_donationStatus.setOnClickListener(v -> {
            if (ClickUtil.isFastClick()) return;
            ForwardDetailsActivity.startActivity(context, donation.getfId());
        });
    }

    private void handleAdvertisementDonation(ReceivedDonationViewHolder viewHolder, Donation donation) {
        Integer status = donation.getStatus();
        if (status != null) {
            if (status == Constant.DONATION_STATUS_COULD_NOT_REVOKE) {
                viewHolder.tv_status.setVisibility(View.VISIBLE);
                viewHolder.tv_status.setText("[广告捐赠]");//显示类型
                viewHolder.tv_status.setTextColor(context.getResources().getColor(R.color.text_gray));

            } else if (status == Constant.DONATION_STATUS_FORWARD) {
                donationHadForward(viewHolder, donation);
            } else {
                Log.e(TAG, "handleAdvertisementDonation: 还有状态未处理" + donation.toString());
            }

        }
    }

    /**
     * 进入捐赠人个人首页
     *
     * @param targetUser
     */
    private void toUserProfile(User targetUser) {
        context.startActivity(new Intent(context, UserProfileActivity.class).putExtra(EaseConstant.EXTRA_TARGET_USER_INFO, targetUser));
    }

    private void donationPraise(Donation donation, ReceivedDonationViewHolder viewHolder) {
        if (!Helper.getInstance().isNetworkConnected()) {
            ((BaseActivity) context).showToast_v1(context.getString(R.string.network_anomalies));
            return;
        }
        Integer praiseSize = donation.getPraiseSize();
        if (praiseSize == null) {
            praiseSize = 0;
        }
        praiseSize++;
        donation.setPraiseSize(praiseSize);
        donation.setHasPraise(true);
        viewHolder.tv_donationPraiseSize.setText(Utils.numberFormat(praiseSize));
        viewHolder.iv_donationPraise.setImageResource(R.drawable.tx_good_red);
        RetrofitManager.getInstance().createRequest(DonationService.class)
                .donationPraise(donation.getId())
                .enqueue(new Callback<CommonResult>() {
                    @Override
                    public void onResponse(Call<CommonResult> call, Response<CommonResult> response) {

                    }

                    @Override
                    public void onFailure(Call<CommonResult> call, Throwable t) {

                    }
                });
    }

    private void removeDonationPraise(Donation donation, ReceivedDonationViewHolder viewHolder) {
        if (!Helper.getInstance().isNetworkConnected()) {
            ((BaseActivity) context).showToast_v1(context.getString(R.string.network_anomalies));
            return;
        }
        Integer praiseSize = donation.getPraiseSize();
        if (praiseSize == null) {
            praiseSize = 1;
        }
        praiseSize--;
        donation.setPraiseSize(praiseSize);
        donation.setHasPraise(false);
        viewHolder.tv_donationPraiseSize.setText(Utils.numberFormat(praiseSize));
        viewHolder.iv_donationPraise.setImageResource(R.drawable.tx_good_gray);
        RetrofitManager.getInstance().createRequest(DonationService.class)
                .removeDonationPraise(donation.getId())
                .enqueue(new Callback<CommonResult>() {
                    @Override
                    public void onResponse(Call<CommonResult> call, Response<CommonResult> response) {

                    }

                    @Override
                    public void onFailure(Call<CommonResult> call, Throwable t) {

                    }
                });
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public int getItemCount() {
        return donationList.size();
    }


    class ReceivedDonationViewHolder extends RecyclerView.ViewHolder {

        @BindView(R.id.iv_avatar)
        ImageView iv_avatar;
        @BindView(R.id.tv_nick)
        TextView tv_name;
        @BindView(R.id.tv_amount)
        TextView tv_amount;
        @BindView(R.id.tv_date)
        TextView tv_date;
        @BindView(R.id.tv_address)
        TextView tv_address;
        @BindView(R.id.tv_extra_message)
        TextView tv_extraMessage;
        @BindView(R.id.tv_status)
        TextView tv_status;
        @BindView(R.id.iv_donation_praise)
        ImageView iv_donationPraise;
        @BindView(R.id.tv_donation_praise_size)
        TextView tv_donationPraiseSize;
        @BindView(R.id.ll_donation_praise)
        LinearLayout ll_donationPraise;
        @BindView(R.id.ll_donation_status)
        LinearLayout ll_donationStatus;

        public ReceivedDonationViewHolder(View itemView) {
            super(itemView);
            ButterKnife.bind(this, itemView);

        }
    }

    public interface InteractionListener {
        void onItemViewClick(String forwardId);

    }

}